/**
 * @author DELL
 * @createDate 2016/11/15 16:43
 * @copyright 广州市生物制品有限公司
 * @description 未经本公司许可，不得以任何方式复制或使用本程序任何部分
 */
package com.lzw;

import com.lzw.command.CreateAccountCommand;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.repository.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.DependsOn;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.util.FileSystemUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.nio.file.Paths;

/**
 * 类功能描述: TODO
 *
 * @author 12360
 * @version 1.0
 * @createDate Nov 19, 2015 11:16:44 AM
 */
@Component
@DependsOn("aggregateAnnotationCommandHandler")
public class Db {

    @Autowired
    @Qualifier("transactionManager")
    protected PlatformTransactionManager txManager;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private Repository repository;

    @Autowired
    private CommandGateway commandGateway;

    @PostConstruct
    private void init() {

        FileSystemUtils.deleteRecursively(Paths.get("./events").toFile());

        CreateAccountCommand accountOne = new CreateAccountCommand("acc-one");
        CreateAccountCommand accountTwo = new CreateAccountCommand("acc-two");

        commandGateway.send(accountOne);
        commandGateway.send(accountTwo);

/*        TransactionTemplate transactionTemplate = new TransactionTemplate(txManager);
         transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                UnitOfWork uow = DefaultUnitOfWork.startAndGet();
                repository.add(new Account("acc-one"));
                repository.add(new Account("acc-two"));
                uow.commit();
            }
        });*/

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.execute("create table account_view(account_no VARCHAR, balance FLOAT)");
        jdbcTemplate.update("insert into account_view(account_no, balance)  values(?,?)", new Object[]{"acc-one", 0.0});
        jdbcTemplate.update("insert into account_view(account_no, balance)  values(?,?)", new Object[]{"acc-two", 0.0});

    }
}
